from django.contrib.auth.backends import ModelBackend, UserModel
from django.db.models import Q
from rest_framework_jwt.utils import jwt_payload_handler as payload_handler

def jwt_payload_handler(user):
    """
    自定义载荷信息
    :params user  用户模型实例对象
    """
    # 先让jwt模块生成自己的载荷信息
    payload = payload_handler(user)
    if hasattr(user, 'avatar'):
        payload['avatar']=user.avatar
    if isinstance(user,"money"):
        payload['money']=float(user,money)
    # 追加自己要返回的内容
    # if hasattr(user, 'avatar'):
    #     payload['avatar'] = user.avatar.url if user.avatar else ""
    # if hasattr(user, 'nickname'):
    #     payload['nickname'] = user.nickname
    #
    # if hasattr(user, 'money'):
    #     payload['money'] = float(user.money)
    # if hasattr(user, 'credit'):
    #     payload['credit'] = user.credit

    return payload

class CustomAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        user=UserModel.objects.filter(Q(username=username)|Q(mobile=username)|Q(email=username)).first()
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user